package com.xuequ.answerme.main;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.os.PersistableBundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.xuequ.answerme.R;
import com.xuequ.answerme.beans.UserBean;
import com.xuequ.answerme.question.AskQuestionActivity;
import com.xuequ.answerme.search.SearchActivity;
import com.xuequ.answerme.tools.FileTools;

import cn.bmob.v3.BmobUser;
import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends AppCompatActivity {

    private TextView mUsername;
    private CircleImageView mAvatar;

    private Toolbar toolBar;
    private DrawerLayout mDrawerLayout;
    private NavigationView mNavigationView;

    private FloatingActionButton main_fab;
    private FloatingActionButton mRefreshFab;
    private FloatingActionButton mQuestionFab;

    private AllFragment allFragment;
    private MeFragment meFragment;
    private StoreFragment storeFragment;

    private boolean isButtonsAppear = false;
    private int fragFlag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.i("main", "---->onCreate");
        initViews();
        setSelect(0);

    }

    /**
     * 初始化控件
     */
    private void initViews() {

        mAvatar = (CircleImageView) findViewById(R.id.drawer_avatar);
        Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/"+ FileTools.AVATAR_NAME);
        mAvatar.setImageBitmap(bitmap);

        //setAvatar
        mUsername = (TextView) findViewById(R.id.drawer_username);
        mUsername.setText(BmobUser.getCurrentUser(MainActivity.this, UserBean.class).getUsername());

        toolBar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolBar);//ToolBar替代ActionBar

        final ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);//设置ActionBar最左边的图标
        actionBar.setDisplayHomeAsUpEnabled(true);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
        if (mNavigationView != null) {
            setupDrawerContent(mNavigationView);
        }

        //button
        main_fab = (FloatingActionButton) findViewById(R.id.main_fab);
        main_fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //toggleMenu
                if(fragFlag != 0){
                    toggleButtons();
                }else {
                    startActivity(new Intent(MainActivity.this,AskQuestionActivity.class));
                }

            }
        });

        mRefreshFab = (FloatingActionButton) findViewById(R.id.main_refresh_fab);
        mRefreshFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //refresh data
                if(fragFlag == 0){
                    allFragment.callToRefreshData();
                }if(fragFlag == 1){
                    storeFragment.callToRefreshData();
                }if(fragFlag == 2){
                    //meFragment.callToRefreshData();
                }
                toggleButtons();
            }
        });

        mQuestionFab = (FloatingActionButton) findViewById(R.id.main_question_fab);
        mQuestionFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,AskQuestionActivity.class));
                toggleButtons();
            }
        });

    }

    /**
     * 开闭菜单
     */
    private void toggleButtons() {
        if (isButtonsAppear) {
            Log.i("toggleButtons", "buttons are ready to disappear");
            // close
            // button alpha 1->0
            // button translationX 0 -> -100

            final PropertyValuesHolder propertyValuesHolder1 = PropertyValuesHolder.ofFloat("translationX", 0);
            final PropertyValuesHolder propertyValuesHolder3 = PropertyValuesHolder.ofFloat("alpha", 1.0f, 0.0f);
            ObjectAnimator animator1 = ObjectAnimator.ofPropertyValuesHolder(mRefreshFab, propertyValuesHolder1, propertyValuesHolder3).setDuration(100);
            animator1.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    mRefreshFab.setClickable(false);

                }

                @Override
                public void onAnimationEnd(Animator animation) {

                    PropertyValuesHolder propertyValuesHolder2 = PropertyValuesHolder.ofFloat("translationX", 0);
                    ObjectAnimator animator2 = ObjectAnimator.ofPropertyValuesHolder(mQuestionFab, propertyValuesHolder3, propertyValuesHolder2).setDuration(100);
                    animator2.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {
                            mQuestionFab.setClickable(false);

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            isButtonsAppear = false;
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    animator2.start();

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            animator1.start();

        } else {
            //open

            Log.i("toggleButtons", "buttons are ready to appear");
            final PropertyValuesHolder propertyValuesHolder4 = PropertyValuesHolder.ofFloat("translationX", -300f);
            final PropertyValuesHolder propertyValuesHolder6 = PropertyValuesHolder.ofFloat("alpha", 0f, 1f);
            ObjectAnimator animator1 = ObjectAnimator.ofPropertyValuesHolder(mRefreshFab, propertyValuesHolder4, propertyValuesHolder6).setDuration(100);
            animator1.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    mRefreshFab.setClickable(true);


                    PropertyValuesHolder propertyValuesHolder5 = PropertyValuesHolder.ofFloat("translationX", -165f);
                    ObjectAnimator animator2 = ObjectAnimator.ofPropertyValuesHolder(mQuestionFab, propertyValuesHolder5, propertyValuesHolder6).setDuration(100);
                    animator2.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {
                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mQuestionFab.setClickable(true);
                            isButtonsAppear = true;
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    animator2.start();

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            animator1.start();
        }
    }

    /**
     * 选择显示哪个Fragment
     * @param position
     */
    private void setSelect(int position) {

        // 声明事物管理
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();

        // 隐藏所有Fragment
        hideFragment(transaction);

        switch (position) {
            case 0:
                if (allFragment == null) {
                    allFragment = new AllFragment();
                    transaction.add(R.id.content_frameLayout, allFragment);
                } else {
                    transaction.show(allFragment);
                }
                toolBar.setTitle("全部");
                fragFlag = 0;
                main_fab.setImageResource(R.drawable.am_question);
                break;
            case 1:
                if (storeFragment == null) {
                    storeFragment = new StoreFragment();
                    transaction.add(R.id.content_frameLayout, storeFragment);
                } else {
                    transaction.show(storeFragment);
                }
                toolBar.setTitle("收藏");
                fragFlag = 1;
                main_fab.setImageResource(R.drawable.am_more);
                break;
            case 2:
                if (meFragment == null) {
                    meFragment = new MeFragment();
                    transaction.add(R.id.content_frameLayout, meFragment);
                } else {
                    transaction.show(meFragment);
                }
                toolBar.setTitle("个人");
                fragFlag = 2;
                main_fab.setImageResource(R.drawable.am_more);
                break;
        }

        if (isButtonsAppear){
            toggleButtons();
        }

        transaction.commit();

    }

    /**
     * 隐藏指定的Fragment
     * @param transaction
     */
    private void hideFragment(FragmentTransaction transaction) {
        if (allFragment != null) {
            transaction.hide(allFragment);
        }

        if (storeFragment != null) {
            transaction.hide(storeFragment);
        }
        if (meFragment != null) {
            transaction.hide(meFragment);
        }
    }

    /**
     * 监听DrawerLayout中的导航菜单。
     * @param navigationView
     */
    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        Log.i("setupDrawerContent", "set");
                        menuItem.setChecked(true);
                        switch (menuItem.toString()) {
                            case "全部":
                                setSelect(0);
                                break;
                            case "收藏":
                                setSelect(1);
                                break;
                            case "个人":
                                setSelect(2);
                                break;
                        }
                        mDrawerLayout.closeDrawers();
                        return true;
                    }
                });
    }

    /**
     * 监听ToolBar上的菜单按钮
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home://如果是菜单按钮
                mDrawerLayout.openDrawer(GravityCompat.START);
                return true;
            case R.id.action_search:
                startActivity(new Intent(MainActivity.this, SearchActivity.class));
                return true;
            case R.id.action_settings:
                Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.action_color:
                Toast.makeText(this, "COLOR", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.action_personal:
                setSelect(2);
                Toast.makeText(this, "PERSONAL", Toast.LENGTH_SHORT).show();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_right, menu);
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    @Override
    protected void onStart() {
        Log.i("main","---->start");
        super.onStart();
    }

    @Override
    protected void onStop() {
        Log.i("main","---->onStop");
        super.onStop();
    }

    @Override
    protected void onRestart() {
        Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/"+ FileTools.AVATAR_NAME);
        mAvatar.setImageBitmap(bitmap);
        mUsername.setText(BmobUser.getCurrentUser(MainActivity.this, UserBean.class).getUsername());

        Log.i("Settings", "------------>----------->------->-------->restart");
        super.onRestart();
    }


}
